<?php

namespace app\store\controller\finance;

use app\store\controller\Controller;
/**
 * 开卡日志
 * Class Count
 * @package app\store\controller
 */
class Opencard extends Controller
{
    /**
     * 开卡消费日志
     */
    public function index() {
        $where = ['um.status' => 1];
        $type = $this->request->param('type/d' , 0);
        if( $type > 0 ) {
            $where['um.pay_type'] = $type;
        }
        $restart = $this->request->param('restart/d' , -1);
        if( $restart >= 0 ) {
            $where['um.restart'] = $restart;
        }
		$newwhere = '';
		$name = $this->request->param("name/s" , '');
		if( $name ) {
			$newwhere = "u.nickname = '{$name}' OR u.user_id = '{$name}'";
		}
        $list = db("member_cart_order")->alias('um')->join("user u" , 'u.user_id = um.user_id')->where($newwhere)->order(['um.pay_time' => 'DESC'])->where($where)->field("um.*,u.nickname")->paginate(15, false, ['query' => $this->request->request()])->each(function($item,$key){
			$item['pay_time'] = date("Y-m-d H:i:s" , $item['pay_time']);
			$item['create_time'] = date("Y-m-d H:i:s" , $item['create_time']);
			return $item;
		});
        return $this->fetch('', compact('list'));
    }
	
	public function export()
    {
		$where = ['um.status' => 1];
        $type = $this->request->param('type/d' , 0);
        if( $type > 0 ) {
            $where['um.pay_type'] = $type;
        }
        $restart = $this->request->param('restart/d' , 0);
        if( $restart > 0 ) {
            $where['um.restart'] = $restart;
        }
		$newwhere = '';
		$name = $this->request->param("name/s" , '');
		if( $name ) {
			$newwhere = "u.nickname = '{$name}' OR u.user_id = '{$name}'";
		}
        $list = db("member_cart_order")->alias('um')->join("user u" , 'u.user_id = um.user_id')->where($newwhere)->order(['um.pay_time' => 'DESC'])->where($where)->field("um.*,u.nickname")->select()->each(function($item,$key){
			$item['pay_time'] = date("Y-m-d H:i:s" , $item['pay_time']);
			$item['create_time'] = date("Y-m-d H:i:s" , $item['create_time']);
			return $item;
		})->toArray();
		$new_data = [];
		if( $list ){
			foreach( $list as $k => $v ) {
				$new_data[] = [
					'id' => $v['id'],
					'nickname' => $v['nickname'],
					'ordersn' => $v['ordersn'],
					'pay_type' => $v['pay_type']==1?'微信':($v['pay_type']==2?'支付宝':'余额'),
					'price' => $v['price'],
					'restart' => $v['restart']==1?'复购':'首次开卡',
					'pay_time' => $v['pay_time'],
					'transaction_id' => $v['transaction_id'],
					'service_num' => $v['service_num'],
					'create_time' => $v['create_time']
				];
			}
		}
		$field = ['ID' , '用户' , '订单编号' , '支付类型' , '支付金额' , '开卡类型','支付时间','支付单号','赠送服务次数','下单时间'];
		\app\common\extend\Excel::export($new_data , $field);
	}
}